package game.gui;


import game.code.Game;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.Timer;

/**
 * The main TextTwist Game GUI 
 * GUI extends JFrame, 
 * has-a Game : provide the the needed methods from the backend.  
 * has-a Timer: refresh every one second, to display the game.timeleft() 
 * 
 * GUI has-a WordList: handles display of result sets.
 *     has-a LetterInventory: six buttons that presenting the scrambled keyword. 
 *     has-a WordFormation  : display the real-time user choosen word to be submitted.
 * 
 * GUI has several inner classes to handle events. 
 *   
 * @author Ying
 *
 */
public class GameGui extends JFrame{

	private Game game ; 

	//Declare handler instance variables
	/**
	 * handles user clicks the startButton
	 */
	private StartHandler startHandler;
	/**
	 * handles time fires every second and display game.timeleft.
	 */
	private TimeHandler timeHandler; 
	
	//declare control instance variables 
	private JLabel textFieldLastWord;
	private JLabel textFieldTimer;	
	private JLabel textFieldHighScore;	
	private JLabel textFieldScore;
	
	private JButton startButton ; 
	private JButton twistButton ; 
	private JButton submitButton;
	private JButton clearButton;
	private JButton backSpaceButton;
	
	private JPanel controlPanel;
	private JPanel buttonPanel; 
	private JPanel displayPanel; 
	
	private WordList wordList ; 
	private LetterInventory letterInventory;
	private WordFormation wordFormation; 
	
	private JPanel rightWrapper ;
	
	private Timer guiTimer ; 
	
	public GameGui(){
		
		super("TextTwist Game GUI");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setSize(640,480);
		setLocation(200,200);
		layoutGUI();

	}
	
	/**
	 * set the layout 
	 */
	public void layoutGUI(){
		
		//all Handlers 
		startHandler = new StartHandler();
		timeHandler = new TimeHandler();

		textFieldScore = new JLabel("Score:");
		textFieldHighScore = new JLabel("High Score:");
		textFieldTimer = new JLabel("Time:");
		textFieldLastWord = new JLabel("Last Word:");
		
		textFieldScore.setFont(Style.gameLableTextFont);
		textFieldHighScore.setFont(Style.gameLableTextFont);
		textFieldTimer.setFont(Style.gameLableTextFont);
		textFieldLastWord.setFont(Style.gameLableTextFont);
		
		//all buttons 
		startButton = new JButton("Start Game");
		startButton.addActionListener(startHandler);
		twistButton = new JButton("Twist");
		twistButton.addActionListener(new ActionListener(){
			@Override
			public void actionPerformed(ActionEvent arg0) {
				letterInventory.twistButtons(game.twist());
			}
		});
		submitButton = new JButton("Submit");
		submitButton.addActionListener(new ActionListener(){
			//user click submit button
			@Override
			public void actionPerformed(ActionEvent e) {
				doSubmit();
			}
			
		});
		
		clearButton = new JButton("Clear");
		clearButton.addActionListener(new ActionListener(){
			//user click the clear key
			@Override
			public void actionPerformed(ActionEvent e) {
				//textArea.setText(lastWord);
				wordFormation.removeWord();
				letterInventory.enableButtons();
			}
		});
		
		backSpaceButton = new JButton("<==");
		backSpaceButton.addActionListener(new ActionListener(){

			@Override
			public void actionPerformed(ActionEvent arg0) {
				// TODO Auto-generated method stub
				letterInventory.enableButton();
				wordFormation.removeTail();
				
			}}
		);
		
		//all Panels 
		controlPanel = new JPanel();
		buttonPanel = new JPanel();
		displayPanel = new JPanel();
		
		wordList = new WordList();
		wordFormation = new WordFormation( );
		letterInventory = new LetterInventory(wordFormation);
		wordFormation.addKeyListener(letterInventory);

		rightWrapper = new JPanel();
		
		loadContent();
		//the game GUI refresh time once per 1 second 
		guiTimer = new Timer(1000,timeHandler); 
		
		setVisible(true);
	}
	
	
	public void loadContent(){
		
		buttonPanel.removeAll();
		displayPanel.removeAll();
		
		//buttonPanel.add(backSpaceButton);
		controlPanel.add(backSpaceButton);
		controlPanel.add(clearButton);
		buttonPanel.add(submitButton);
		buttonPanel.add(twistButton);
		//buttonPanel.add(clearButton);
		buttonPanel.add(startButton);

		displayPanel.add(textFieldTimer);
		displayPanel.add(textFieldHighScore);
		displayPanel.add(textFieldScore);
		displayPanel.add(textFieldLastWord);
	
		rightWrapper.removeAll();
		
		rightWrapper.setLayout(new BoxLayout(rightWrapper,BoxLayout.Y_AXIS));
		rightWrapper.add(wordFormation);
		rightWrapper.add(controlPanel);
		rightWrapper.add(letterInventory);
		rightWrapper.add(buttonPanel);
		rightWrapper.add(displayPanel);
		
		//Main Container
		getContentPane().removeAll();
		getContentPane().add(new JScrollPane(wordList),BorderLayout.WEST);
		getContentPane().add(rightWrapper,BorderLayout.EAST);
		getContentPane().repaint();
	}
	
	/**
	 * called by keyListener and click(action) listner
	 */
	private void doSubmit(){
		String word = wordFormation.getWord();
		if (word.length()==0) return ;
		
		int index = game.getPlayer().submit(word);
		if(index>=0){
			textFieldScore.setText("Score:"+Integer.toString(game.score()));
			wordList.wordsVectorArr[word.length()][index] = word;
			getContentPane().repaint();
		}
		
		wordFormation.removeWord();
		letterInventory.enableButtons();
		textFieldLastWord.setText("Last Word: "+word);
		
		if(game.getPlayer().isLastSubmit()){
			game.over();
			//a pop-up message to user game is end.
			JOptionPane.showMessageDialog(null, "Game end. Your Score is: " +
					game.getPlayer().score());

		}
	}
	
	//user click start button
	class StartHandler implements ActionListener{
		@Override
		public void actionPerformed(ActionEvent e) {
			
			game = Game.getGame();

			//check is first time run start. if not re-start.
			if(game.isFirstRun()){
				game.start();
			}
			else {
				//will not load again from dictionary file
				game.reStart();	
				textFieldLastWord.setText("Last Word:");
			}
			
			textFieldHighScore.setText("High Score:"+ Integer.toString(game.highScore()));
			textFieldScore.setText("Score:" + game.getPlayer().score());
			wordList.loadList(game.numberOfWordsByLength());
			letterInventory.twistButtons(game.twist());
			loadContent();
			guiTimer.start();
		}
	}
	
	
	/**
	 * An inner class. 
	 * listen to the guiTimer fired one per second, display the game 
	 * timeLeft on the GUI.
	 * 
	 */
	class TimeHandler implements ActionListener{

		@Override
		public void actionPerformed(ActionEvent arg0) {
			textFieldTimer.setText("Time:"+ Integer.toString(game.timeLeft()));
			if(game.timeLeft()==0){
				guiTimer.stop();

				JOptionPane.showMessageDialog(null, "Game end. Your Score is: " +
						game.getPlayer().score());
			}
		}
	}

	
	public static void main(String[] args){
		new GameGui();
	}
	
	
}
